package com.easy.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easy.common.bean.DeliveryAddr;
import com.easy.common.service.IDeliveryAddrService;
import com.easy.common.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user/deliveryaddr")
@CrossOrigin
public class DeliveryAddrController {

    @Autowired
    IDeliveryAddrService deliveryAddrService;

    // 根据id获取地址信息
    @GetMapping("/id/{id}")
    public Result getAddrById(@PathVariable Integer id) {
        return Result.success(deliveryAddrService.getAddrById(id));
    }

    // 根据用户id获取地址列表
    @GetMapping("/user/{userId}")
    public Result getAddrsByUserId(@PathVariable Integer userId) {
        return Result.success(deliveryAddrService.getAddrsByUserId(userId));
    }

    // 添加地址
    @PostMapping("/add")
    public Result addAddr(@RequestBody DeliveryAddr deliveryAddr) {
        int result = deliveryAddrService.addAddr(deliveryAddr);
        return result > 0 ? Result.success("添加成功") : Result.fail(500, "添加失败");
    }

    // 更新地址
    @PutMapping("/update")
    public Result updateAddr(@RequestBody DeliveryAddr deliveryAddr) {
        int result = deliveryAddrService.updateAddr(deliveryAddr);
        return result > 0 ? Result.success("更新成功") : Result.fail(500, "更新失败");
    }

    // 删除地址（软删除）
    @DeleteMapping("/delete/{id}")
    public Result deleteAddr(@PathVariable Integer id) {
        int result = deliveryAddrService.deleteAddr(id);
        return result > 0 ? Result.success("删除成功") : Result.fail(500, "删除失败");
    }

//    // 设置默认地址
//    @PutMapping("/default/{id}")
//    public Result setDefaultAddr(@PathVariable Integer id, @RequestParam Integer userId) {
//        int result = deliveryAddrService.setDefaultAddr(id, userId);
//        return result > 0 ? Result.success("设置成功") : Result.fail(500, "设置失败");
//    }

    // 获取地址列表
    @GetMapping("/list")
    public Result getAddrList(DeliveryAddr deliveryAddr) {
        return Result.success(deliveryAddrService.getAll(deliveryAddr));
    }

    // 获取地址分页列表
    @GetMapping("/page")
    public Result getAddrPage(DeliveryAddr deliveryAddr, Integer current, Integer size) {
        IPage<DeliveryAddr> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size);
        return Result.success(deliveryAddrService.getPage(deliveryAddr, page));
    }
}
